package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次请求的uri
        String requestURI = request.getRequestURI();
        log.info("本次请求的uri:{}",requestURI);
        String[] uris = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "common/**"
        };
        //判断本次请求是否需要处理
        boolean check = check(uris, requestURI);
        //如果不需要处理，则直接放行
        if (check) {
            log.info("本次请求：{}，已被放行",requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        //判断登录状态，如果已登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("employee");
        if (userId != null) {
            log.info("用户已登录，用户id为{}",userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        //如果未登录则返回未登录结果
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public boolean check(String[] uris, String requestURI) {
        for (String uri : uris) {
            boolean check = ANT_PATH_MATCHER.match(uri, requestURI);
            if (check) {
                return true;
            }
        }
        return false;
    }
}
